import NProgress from "@/plugins/nprogress";
import { getToken } from "@/plugins/auth";
import router from "@/router";
import { Login } from "@/layouts/components/Login/utils";

export function setupPermission() {
  // 白名单路由
  const whiteList = ["/", "/test"];

  router.beforeEach(async (to, _, next) => {
    NProgress.start();
    const isLogin = !!getToken(); // 判断是否登录
    if (isLogin) {
      if (to.matched.length === 0) {
        // 路由未匹配，跳转到404
        next("/404");
      } else {
        // 动态设置页面标题
        const title = to.params.title || to.query.title;
        if (title) {
          to.meta.title = title;
        }
        next();
      }
    } else {
      // 未登录，判断是否在白名单中
      if (whiteList.includes(to.path)) {
        next();
      } else {
        NProgress.done();
        Login();
        // 不在白名单，重定向到登录页
        next("/login");
      }
    }
  });

  // 后置守卫，保证每次路由跳转结束时关闭进度条
  router.afterEach(() => {
    NProgress.done();
  });
}
